package com.wavercaz.freeforum.controllers;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wavercaz.freeforum.pojo.*;
import com.wavercaz.freeforum.pojo.vo.PostVo;
import com.wavercaz.freeforum.services.PostFeedbackService;
import com.wavercaz.freeforum.services.PostReplyService;
import com.wavercaz.freeforum.services.PostService;
import com.wavercaz.freeforum.utils.JWTUtil;
import com.wavercaz.freeforum.utils.QueryUtil;
import com.wavercaz.freeforum.utils.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
public class PostController {
    @Autowired
    private  PostService postService;
    @Autowired
    private PostFeedbackService postFeedbackService;
    @Autowired
    private PostReplyService postReplyService;

    // 增
    @PutMapping("/post")
    @Transactional
    public ResponseResult save(@RequestHeader("Authorization") String token ,@RequestBody Post post) {
        post.setUserId(Integer.parseInt(JWTUtil.verifyToken(token).getClaim("id").asString()));
        post.setStatus(1);
        boolean result = postService.save(post);
        PostReply postReply = new PostReply(null, post.getUserId(), post.getId(), post.getContent(), 1, post.getPublishDateByLocalDateTime());
        postReplyService.save(postReply);
        if(!result) return new ResponseResult(HttpStatus.NO_CONTENT.value(), "新增失败");
        else return new ResponseResult(HttpStatus.OK.value(), "新增成功",post);
    }

    // 删
    @DeleteMapping("/post")
    public ResponseResult delete(@RequestBody List<Integer> ids) {
        boolean result = postService.removeByIds(ids);
        ids.forEach(v -> {
            postReplyService.remove(new QueryWrapper<PostReply>().eq("post_id",v));
        });
        if(!result) return new ResponseResult(HttpStatus.NO_CONTENT.value(), "删除失败");
        else return new ResponseResult(HttpStatus.OK.value(), "删除成功");
    }

    // 改
    @PostMapping("/post")
    @Transactional
    public ResponseResult update(@RequestBody Post post) {
        boolean result = postService.updateById(post);
        PostReply postReply = postReplyService.getOne(new QueryWrapper<PostReply>()
                .eq("post_id", post.getId()).eq("is_first", 1));
        postReply.setContent(post.getContent());
        postReplyService.updateById(postReply);
        if(!result) return new ResponseResult(HttpStatus.NO_CONTENT.value(), "修改失败");
        else return new ResponseResult(HttpStatus.OK.value(), "修改成功");
    }

    // 查
    @GetMapping("/post/{id}")
    public ResponseResult get(@PathVariable Integer id ) {
        Post post = postService.getById(id);
        if(post == null) return new ResponseResult(HttpStatus.NO_CONTENT.value(), "无此相关信息");
        else return new ResponseResult(HttpStatus.OK.value(), post);
    }

    // 列表
    @PostMapping("/postList")
    public ResponseResult list(@RequestBody(required = false) CommonSearchParam commonSearchParam) {
        Object data = null;
        if(commonSearchParam != null) {
            QueryWrapper queryWrapper = QueryUtil.getQueryWrapper(commonSearchParam.getSearches());
            if(commonSearchParam.getPageNum()!=null && commonSearchParam.getPageSize()!=null)
                data= postService.page(new Page<>(commonSearchParam.getPageNum(), commonSearchParam.getPageSize()), queryWrapper);
            else data= postService.list(queryWrapper);
        }
        else data= postService.list();
        return new ResponseResult(HttpStatus.OK.value(), data);
    }

    // vo列表
    @PostMapping("/postVoList")
    public ResponseResult listVo(@RequestHeader(value = "Authorization",required = false) String token, @RequestBody CommonSearchParam commonSearchParam) {
        CommonSearchParam.Search[] searches = commonSearchParam.getSearches() != null ? commonSearchParam.getSearches() : new CommonSearchParam.Search[0];
        String type = "allList";
        IPage<PostVo> data = null;
        for (CommonSearchParam.Search search : searches) {
            type = search.getKey().equals("is_collect") ? "collectList" : type;
        }
        if(type.equals("collectList")) {
            data = getColoectlistVo(commonSearchParam);
        } else {
            data = postService.getPostVoList(commonSearchParam, new Page<>(commonSearchParam.getPageNum(), commonSearchParam.getPageSize()));
            if(token != null) {
                /// 获取当前用户下的反馈数据（点赞、收藏信息）
                List<PostFeedback> postFeedbacks = postFeedbackService.list(new QueryWrapper<PostFeedback>().eq("user_id", Integer.parseInt(JWTUtil.verifyToken(token).getClaim("id").asString())));
                // 将查询出来的帖子数据转换为map，然后根据反馈数据设置帖子对于该用户的点赞、收藏情况
                Map<Integer, PostVo> postVoMap = data.getRecords().stream()
                        .collect(Collectors.toMap(PostVo::getId, p -> p));
                for (PostFeedback postFeedback:postFeedbacks) {
                    PostVo postVo = postVoMap.get(postFeedback.getPostId());
                    if(postVo != null) {
                        postVo.setIsLike(postFeedback.getIsLike());
                        postVo.setIsCollect(postFeedback.getIsCollect());
                    }
                }
                List<PostVo> postVoList = postVoMap.values().stream()
                        .collect(Collectors.toList());
                data.setRecords(postVoList);
            }
        }
        // 如果data为null，那就返回一个空列表
        return new ResponseResult(HttpStatus.OK.value(), data == null?new ArrayList<>():data);
    }

    // 收藏Vo列表
    public IPage getColoectlistVo(@RequestBody CommonSearchParam commonSearchParam) {
        Integer userId = null;
        for (CommonSearchParam.Search search : commonSearchParam.getSearches()) {
            userId = search.getKey().equals("post.user_id") ? (Integer) search.getValue() : userId;
        }
        List<PostFeedback> postFeedbacks = postFeedbackService.list(new QueryWrapper<PostFeedback>().eq("user_id", userId).eq("is_collect",0));
        ArrayList<Integer> postIds = new ArrayList<>();
        postFeedbacks.forEach(v -> {
            postIds.add(v.getPostId());
        });
        // 若postIds的长度为空，则证明用户没有收藏任何帖子，因此赋值-1，满足sql语句的语法的前提让查询数据返回空列表
        if(postIds.size() == 0) postIds.add(-1);
        CommonSearchParam.Search[] searches = commonSearchParam.getSearches();
        for (int i = 0; i < searches.length; i++) {
            if(searches[i].getKey().equals("is_collect")) {
                searches[i] = new CommonSearchParam.Search("post.id","in",postIds);
            }
        }
        IPage<PostVo> data = postService.getPostVoList(commonSearchParam, new Page<>(commonSearchParam.getPageNum(), commonSearchParam.getPageSize()));
        System.out.println(data);
        Map<Integer, PostVo> postVoMap = data.getRecords().stream()
                .collect(Collectors.toMap(PostVo::getId, p -> p));
        for (PostFeedback postFeedback:postFeedbacks) {
            PostVo postVo = postVoMap.get(postFeedback.getPostId());
            if(postVo != null) {
                postVo.setIsLike(postFeedback.getIsLike());
                postVo.setIsCollect(postFeedback.getIsCollect());
            }
        }
        List<PostVo> postVoList = postVoMap.values().stream()
                .collect(Collectors.toList());
        data.setRecords(postVoList);
        return data;
    }
}
